'''
Author: tsg sanguitang@163.com
Date: 2023-05-29 17:58:19
LastEditors: tsg sanguitang@163.com
LastEditTime: 2023-05-29 18:16:34
FilePath: \hello_world\main\test.py
Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
'''
import re
import base64
from Crypto.Cipher import AES
import copy

class AesCbc:
    def __init__(self):
        self.key = b'4cTjUP2^ZO8NiUr4'          # 定义key值
        self.iv = b'u4k8IMf89@LVCID4'           # 定义iv值
        self.mode = AES.MODE_CBC
        self.bs = 16                            # block size
        self.PADDING = lambda s: s + (self.bs - len(s) % self.bs) * chr(self.bs - len(s) % self.bs).encode('utf-8')
 
    def encrypt(self, text):
        print("[Send]: ", text)
        generator = AES.new(self.key, self.mode,self.iv)    #这里的key 和IV 一样 ，可以按照自己的值定义
        btext=text.encode()
        # self.PADDING(btext)
        encrypt_bytes = generator.encrypt(self.PADDING(btext))
        encrypt_str = base64.b64encode(encrypt_bytes)   #输出Base64

        result_bytes = encrypt_str.decode()
        # print("after:", result_bytes)
        return copy.copy(result_bytes)
 
    def decrypt(self, text):
        # print("decrypt:", text)
        generator = AES.new(self.key, self.mode,self.iv)
        text += (len(text) % 4) * '='
        decrpyt_bytes = base64.b64decode(text)           #输出Base64
        msg = generator.decrypt(decrpyt_bytes)
        # 去除解码后的非法字符
        try:
            result_str = re.compile('[\\x00-\\x08\\x0b-\\x0c\\x0e-\\x1f\r\t]').sub('', msg.decode())
        except Exception:
            result_str = '解码失败，请重试!'
        print("[Recv]: ", result_str)
        return copy.copy(result_str)
 
 
if __name__ == '__main__':
    aes = AesCbc()
 
    to_encrypt = '''{"messageType":"mqttSubData","deviceTime":"2022-12-12 10:00:00","data":{"topicValue":"WT10/866248053263826,/WT10","deviceKey":"866248053263826","projectKey":"chiot_student_card","status":"1","serverInfo":"221.10.90.142:18190"},"commandNumber":"12345233","imei":"866248053263826","dataType":"1"}'''
    to_decrypt = '5139221b05a77c67c4bacb05e566ae91'
    #解密不需要偏移量
    buffer = aes.encrypt(to_encrypt)
    print(type(buffer))
    
    print("\n加密前:{0}\n加密后:{1}\n".format(to_encrypt,buffer))
    print("解密前:{0}\n解密后:{1}".format(buffer,aes.decrypt(buffer)))